package cn.com.smart.form.parser.factory;

import cn.com.smart.form.parser.IFormParser;
import cn.com.smart.service.SmartContextService;
import com.mixsmart.utils.StringUtils;

import java.util.List;

/**
 * 表单解析工厂
 * @author lmq
 * @create 2015年7月4日
 * @version 1.0 
 * @since
 */
public class FormParserFactory {

	private List<IFormParser> formParsers;
	
	private static FormParserFactory instance = new FormParserFactory();
	
	private FormParserFactory() {
		formParsers = SmartContextService.finds(IFormParser.class);
	}
	
	public static FormParserFactory getInstance() {
		return instance;
	}
	
	/**
	 * 获取解析器
	 * @param plugin
	 * @return
	 * @throws NotFindParserException
	 */
	public IFormParser getParser(String plugin) throws NotFindParserException {
	    IFormParser formParser = null;
		if(StringUtils.isNotEmpty(plugin) && null != formParsers && formParsers.size()>0) {
			for (IFormParser formParserTmp : formParsers) {
				if(formParserTmp.getPlugin().equals(plugin)) {
				    formParser = formParserTmp;
				    break;
				}
			}
		}
		if(null == formParser) {
		    throw new NotFindParserException(plugin);
		} else {
		    return formParser;
		}
	}
	 
	
	/**
	 * 注册解析器
	 * @param formParser
	 * @return
	 */
	public boolean register(IFormParser formParser) {
		boolean is = false;
		if(null != formParser) {
			formParsers.add(formParser);
			is = true;
		}
		return is;
	}
	
	
	/**
	 * 注册解析器
	 * @param parsers
	 * @return
	 */
	public boolean register(List<IFormParser> parsers) {
		boolean is = false;
		if(null != parsers && parsers.size()>0) {
			formParsers.addAll(parsers);
			is = true;
		}
		return is;
	}
	
}
